package edu.zhuoxun.blogserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.zhuoxun.blogserver.entity.Permission;
import edu.zhuoxun.blogserver.entity.Result;
import edu.zhuoxun.blogserver.entity.Role;
import edu.zhuoxun.blogserver.map.PermissionMapper;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class PermissionController {
    @Autowired
    public PermissionMapper permissionMapper;

    @GetMapping("/api/permission/list")
    @ResponseBody
    @RequiresPermissions("permission:view")
    public Result<List<Permission>> getAllPermissions() {
        Result<List<Permission>> result = new Result<>();
        result.setCode(200);
        result.setMessage("OK");
        result.setData(permissionMapper.selectList(new QueryWrapper<>()));
        return result;
    }

    @PostMapping("/api/permission/has")
    @ResponseBody
    @RequiresPermissions("permission:view")
    public Result<List<Permission>> getHasPermissions(@RequestBody Role role) {
        Result<List<Permission>> result = new Result<>();
        result.setCode(200);
        result.setMessage("OK");
        result.setData(permissionMapper.getPermissionsByRole(role));
        return result;
    }

    @PostMapping("/api/permission/save")
    @ResponseBody
    @RequiresPermissions(value = {"permission:add", "permission:update"}, logical = Logical.OR)
    public Result<Void> savePermission(@RequestBody Permission permission) {
        Result<Void> result = new Result<>();
        if (permission.getId() == null) {
            permissionMapper.insert(permission);
        } else {
            permissionMapper.updateById(permission);
        }
        result.setCode(200);
        result.setMessage("OK");
        return result;
    }

    @PostMapping("/api/permission/delete")
    @ResponseBody
    @RequiresPermissions("permission:delete")
    public Result<Void> deletePermission(@RequestBody List<Permission> permissions) {
        Result<Void> result = new Result<>();
        permissionMapper.deleteBatchIds(permissions.stream().map(Permission::getId).collect(Collectors.toList()));
        result.setCode(200);
        result.setMessage("OK");
        return result;
    }

}
